import 'dart:io';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:jet_rails/jr_app/jr_models/jr_article_model.dart';
import 'package:jet_rails/jr_app/jr_models/jr_user_model.dart';
import 'package:jet_rails/jr_services/jr_services.dart';
import 'package:jet_rails/jr_utils/jr_file.dart';
import 'package:jet_rails/jr_utils/jr_logger.dart';
import 'package:jet_rails/jr_utils/jr_media.dart';
import 'package:jet_rails/jr_utils/jr_toast.dart';
import 'package:path_provider/path_provider.dart';

class JrDiscoveryController extends GetxController {
  final postContentLength = 0.obs;
  final translatedArticle = ''.obs;
  final postImageList = <String>[].obs;

  Future<void> refreshArticleList() async {
    JrServices.instance.allArticle.refresh();
    JrServices.instance.saveArticle();
  }

  void addPostImage() async {
    String? imgPath = await JrMedia.instance.pickImage();
    if (imgPath != null) {
      Directory directory = await getTemporaryDirectory();
      String name = imgPath.split('/').last;
      String destPath = '${directory.path}/article/${JrServices.instance.loginUser.value.userId!}/$name';
      await JrFile.copyFile(imgPath, destPath);
      postImageList.add(destPath);
    }
  }

  void postArticle(String title, String description) async {
    try {
      EasyLoading.show();
      await Future.delayed(const Duration(seconds: 2));
      final my = JrServices.instance.loginUser.value;
      JrArticleModel articleModel = JrArticleModel(
        title: title,
        description: description,
        author: JrUserModel(
          nickname: my.nickname,
          avatar: my.getAvatarUrl,
          userId: my.userId ?? '',
        ),
        authorCode: '',
        followed: 1,
        count: 0,
        thumbnail: postImageList.value.elementAt(0),
        content: postImageList.value,
        commentList: [],
        likedByMe: true
        
      );
      JrServices.instance.allArticle.value.insert(0, articleModel);
      refreshArticleList();
      JrServices.instance.saveArticle();
      Get.back();
      JrToast.show('Posted successfully');
    } catch (e) {
      JrLogger.e('$e');
    } finally {
      EasyLoading.dismiss();
    }
  }

  void toggleLikeStatus(JrArticleModel item) {
    if (item.likedByMe == true) {
      item.likedByMe = false;
      item.followed = item.followed - 1;
    } else {
      item.likedByMe = true;
      item.followed = item.followed + 1;
    }
    refreshArticleList();
    JrServices.instance.saveArticle();
  }
}
